from django.contrib.auth.models import User
from rest_framework import serializers

from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES

# class SnippetSerializer(serializers.Serializer):
#     id = serializers.IntegerField(read_only=True) # read_only只读
#     title = serializers.CharField(required=False, allow_blank=True, max_length=100) # required设定改字段能否为空
#     code = serializers.CharField(style={'base_template': 'textarea.html'})
#     linenos = serializers.BooleanField(required=False)
#     langugae = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
#     style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

#     def create(self, validated_data):
#         """
#         给定验证后的数据，创建并返回一个新的'Snippet'实例
#         """
#         return Snippet.objects.create(**validated_data)

#     def update(self, instance, validated_data):
#         """
#         给定验证过的数据，更新并返回一个现有的'Snippet'实例
#         """
#         instance.title = validated_data.get('title', instance.title)
#         instance.code = validated_data.get('code', instance.code)
#         instance.linenos = validated_data.get('linenos', instance.linenos)
#         instance.language = validated_data.get('language', instance.language)
#         instance.style = validated_data.get('style', instance.style)
#         instance.save()
#         return instance

class SnippetSerializer(serializers.ModelSerializer):
    """
    ModelSerializer类提供了快捷方式，可以让你自动创建一个Serializer类对应于模型字段的字段
    与常规Serializer类不同之处在于：
    ·它将根据模型自动为您生成一组字段
    ·它将自动为序列化器生成验证器，例如unique_together验证器
    ·它包括简单的默认实现.create()和.update()
    """
    class Meta:
        model = Snippet
        # fields = ('id', 'title', 'code', 'linenos', 'langugae', 'style') 
        # '__all__'以指示使用模型中的所有字段
        fields = '__all__'


# class SnippetSerializer(serializers.HyperlinkedModelSerializer):
#     id = serializers.ReadOnlyField(source='owner.username')
#     highlight = serializers.HyperlinkedIdentityField(
#         view_name='snippet-highlight', format='html')

#     class Meta:
#         model = Snippet
#         firlds = ('url', 'id', 'highlight', 'owner', 'title', 'code',
#                     'linenos', 'language', 'style')

# class UserSerializer(serializers.HyperlinkedModelSerializer):
#     snippets = serializers.HyperlinkedIdentityField(
#         many=True, view_name='snippet-detail', read_only=True)

#     class Meta:
#         model = User
#         fields = ('url', 'id', 'username', 'snippets')

